package com.algo.moduleThree;

import java.util.HashMap;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class InAndPostBuildTree {

    HashMap<Integer, Integer> inOrderMap = new HashMap<>();

    int[] post;

    public TreeNode buildTree(int[] inorder, int[] postorder) {

        for (int i = 0; i < inorder.length; i++) {
            inOrderMap.put(inorder[i], i);
        }
        post = postorder;
        TreeNode root = buildTree(0, inorder.length - 1, 0, postorder.length - 1);
        return root;

    }

    private TreeNode buildTree(int is, int ie, int ps, int pe) {

        // 终止条件：左指针遍历完
        if (is > ie || ps > pe) {
            return null;
        }
        // 以后序遍历为主还原二叉树
        int root = post[pe];
        // 查找root 所在中序根节点对应的值
        Integer ri = inOrderMap.get(root);
        // 组装成 TreeNode
        TreeNode node = new TreeNode(root);
        // 递归 中序、后序左子树
        node.left = buildTree(is, ri - 1, ps, ps + ri - is - 1);
        // 递归 中序、后序右子树
        node.right = buildTree(ri+1, ie, ps + ri - is , pe- 1);
        return  node;
    }
}
